import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// Vant声明和按需引入
import Components from 'unplugin-vue-components/vite'
import { VantResolver } from 'unplugin-vue-components/resolvers'
import postCssPxToRem from 'postcss-pxtorem'

// https://vitejs.dev/config/
export default defineConfig(({ command, mode, isSsrBuild, isPreview }) => {
  console.log('vite config:', command, mode, isSsrBuild, isPreview)

  const base = {
    define: {
      __APP_VERSION__: require('./package.json').version,
      __APP_BUILD_DATE__: JSON.stringify(new Date().toLocaleString()),
    },
    server: {
      open: true,
    },
    plugins: [
      vue(),
      Components({
        resolvers: [VantResolver()],
      }),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true,
          additionalData: `@import "@/styles/variable.scss";`,
        },
      },
      postcss: {
        plugins: [
          postCssPxToRem({
            rootValue: 37.5,
            propList: ['*'], // 需要转换的css属性，默认*全部
            selectorBlackList: ['appview'],
          }),
        ],
      },
    },
  }
  if (mode !== 'production') {
    return {
      // dev 独有配置
      ...base,
    }
  } else {
    return {
      // build 独有配置
      ...base,
      esbuild: {
        // 打包时移除 console.log
        pure: ['console.log'],
        // 打包时移除 debugger
        drop: ['debugger'],
        // 打包时移除所有注释
        legalComments: 'none',
      },
    }
  }
})
